<template>
  <div class="modules-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2 class="page-title">
          <el-icon><Grid /></el-icon>
          模块列表
        </h2>
        <p class="page-description">
          {{ currentProductName }} - 共 {{ modules.length }} 个模块
        </p>
      </div>
      <div class="header-actions">
        <el-button
          type="primary"
          :icon="Refresh"
          @click="refreshData"
          :loading="loading"
        >
          刷新数据
        </el-button>
        <el-button
          :icon="Download"
          @click="exportData"
        >
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="搜索模块">
          <el-input
            v-model="searchForm.keyword"
            placeholder="输入模块名称搜索..."
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="模块类型">
          <el-select
            v-model="searchForm.type"
            placeholder="全部类型"
            clearable
            @change="handleSearch"
            style="width: 150px"
          >
            <el-option label="可执行文件" value="executable" />
            <el-option label="动态库" value="dylib" />
            <el-option label="框架" value="framework" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :icon="Filter" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <el-card
        v-for="stat in moduleStats"
        :key="stat.label"
        class="stat-card"
        shadow="hover"
      >
        <div class="stat-content">
          <div class="stat-icon" :style="{ backgroundColor: stat.color + '20' }">
            <el-icon :style="{ color: stat.color }" :size="24">
              <component :is="stat.icon" />
            </el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-label">{{ stat.label }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 模块表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="filteredModules"
        style="width: 100%"
        row-key="id"
        @sort-change="onSortChange"
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="模块名称" min-width="200" sortable="custom">
          <template #default="{ row }">
            <el-link
              type="primary"
              :underline="false"
              @click="viewModuleDetail(row.id)"
            >
              {{ row.name }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="dependencies" label="依赖个数" width="100" align="center" sortable="custom">
          <template #default="{ row }">
            <el-tag
              :type="row.dependencies > 10 ? 'danger' : row.dependencies > 5 ? 'warning' : 'success'"
              size="small"
            >
              {{ row.dependencies }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dependedBy" label="被依赖" width="100" align="center" sortable="custom">
          <template #default="{ row }">
            <el-tag type="info" size="small">{{ row.dependedBy || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小" width="120" sortable="custom">
          <template #default="{ row }">
            {{ formatBytes(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="memory" label="内存占用" width="120" sortable="custom">
          <template #default="{ row }">
            {{ formatBytes(getMemoryUsage(row)) }}
          </template>
        </el-table-column>
        <el-table-column prop="processCount" label="引用进程数" width="120" align="center" sortable="custom">
          <template #default="{ row }">
            <el-tag type="info" size="small">{{ getProcessCount(row.procesess) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              link
              @click="viewModuleDetail(row.id)"
            >
              详情
            </el-button>
            <el-button
              size="small"
              type="success"
              link
              @click="openDependencyDialog(row.id)"
            >
              依赖
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 模块详情对话框 -->
    <ModuleDetailDialog
      v-model="detailDialogVisible"
      :module-id="selectedModuleId"
      @close="handleDetailClose"
      @open-dependency-context="handleOpenDependencyContext"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Grid,
  Refresh,
  Download,
  Search,
  Filter,
  DataBoard,
  Link,
  Monitor,
  Cpu
} from '@element-plus/icons-vue'
import { useModulesStore } from '@/stores/modules'
import { formatBytes } from '@/utils/format'
import ModuleDetailDialog from '@/components/ModuleDetailDialog.vue'

const modulesStore = useModulesStore()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const searchForm = reactive({
  keyword: '',
  type: ''
})

// 排序状态
const sortState = reactive({
  field: null,
  order: null
})

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0
})

const detailDialogVisible = ref(false)
const selectedModuleId = ref(null)

// 获取内存使用量
const getMemoryUsage = (module) => {
  return module.pss || module.memoryUsage || module.memory || module.size || 0
}

// 获取进程数量
const getProcessCount = (processes) => {
  if (!processes) return 0
  const processList = processes.split(',').filter(p => p.trim())
  return processList.length
}

// 计算属性
const modules = computed(() => modulesStore.modules)
const currentProductName = computed(() => modulesStore.currentProductName)

// 排序函数
const sortModules = (modules) => {
  if (!sortState.field || !sortState.order) {
    return modules
  }

  return [...modules].sort((a, b) => {
    let aVal, bVal

    switch (sortState.field) {
      case 'name':
        aVal = a.name || ''
        bVal = b.name || ''
        return sortState.order === 'ascending'
          ? aVal.localeCompare(bVal)
          : bVal.localeCompare(aVal)

      case 'dependencies':
        aVal = a.dependencies || 0
        bVal = b.dependencies || 0
        break

      case 'dependedBy':
        aVal = a.dependedBy || 0
        bVal = b.dependedBy || 0
        break

      case 'size':
        aVal = a.size || 0
        bVal = b.size || 0
        break

      case 'memory':
        aVal = getMemoryUsage(a)
        bVal = getMemoryUsage(b)
        break

      case 'processCount':
        aVal = getProcessCount(a.procesess)
        bVal = getProcessCount(b.procesess)
        break

      default:
        return 0
    }

    // 数字比较
    if (sortState.order === 'ascending') {
      return aVal - bVal
    } else {
      return bVal - aVal
    }
  })
}

// 过滤后的模块
const filteredModules = computed(() => {
  let filtered = modules.value

  if (searchForm.keyword) {
    filtered = filtered.filter(module =>
      module.name.toLowerCase().includes(searchForm.keyword.toLowerCase())
    )
  }

  if (searchForm.type) {
    filtered = filtered.filter(module => {
      if (searchForm.type === 'dylib') {
        return module.name.includes('.dylib')
      } else if (searchForm.type === 'executable') {
        return !module.name.includes('.dylib')
      }
      return true
    })
  }

  // 应用排序
  filtered = sortModules(filtered)

  pagination.total = filtered.length
  const start = (pagination.current - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filtered.slice(start, end)
})

// 模块统计
const moduleStats = computed(() => {
  const stats = {
    total: modules.value.length,
    dylibs: modules.value.filter(m => m.name.includes('.dylib')).length,
    executables: modules.value.filter(m => !m.name.includes('.dylib')).length,
    totalDeps: modules.value.reduce((sum, m) => sum + (m.dependencies || 0), 0)
  }

  return [
    {
      label: '总模块数',
      value: stats.total,
      icon: 'Grid',
      color: '#409EFF'
    },
    {
      label: '动态库',
      value: stats.dylibs,
      icon: 'Link',
      color: '#67C23A'
    },
    {
      label: '可执行文件',
      value: stats.executables,
      icon: 'Monitor',
      color: '#E6A23C'
    },
    {
      label: '总依赖数',
      value: stats.totalDeps,
      icon: 'DataBoard',
      color: '#F56C6C'
    }
  ]
})

// 方法
const refreshData = async () => {
  loading.value = true
  try {
    await modulesStore.fetchModules()
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  } finally {
    loading.value = false
  }
}

const exportData = () => {
  if (modules.value.length === 0) {
    ElMessage.warning('暂无数据可导出')
    return
  }

  ElMessageBox.confirm(
    `确定要导出全部 ${modules.value.length} 个模块的数据吗？`,
    '确认导出',
    {
      type: 'info',
      confirmButtonText: '导出CSV',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    try {
      exportModulesToCSV(modules.value)
      ElMessage.success('模块数据导出成功')
    } catch (error) {
      console.error('Export failed:', error)
      ElMessage.error('导出失败，请重试')
    }
  }).catch(() => {
    // 用户取消
  })
}

// 导出模块数据到CSV
const exportModulesToCSV = (modulesToExport) => {
  const timestamp = new Date().toISOString().slice(0, 19).replace(/[:-]/g, '')
  const productName = modulesStore.currentProduct || 'Unknown'
  const productVersion = modulesStore.currentVersion || 'Unknown'
  const fileName = `modules_${productName}_${productVersion}_${timestamp}.csv`

  // 生成CSV内容
  const csvContent = generateModulesCSV(modulesToExport, productName, productVersion)

  // 创建Blob并下载
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)

  link.setAttribute('href', url)
  link.setAttribute('download', fileName)
  link.style.visibility = 'hidden'

  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)

  URL.revokeObjectURL(url)
}

// 生成模块数据CSV内容
const generateModulesCSV = (data, productName, productVersion) => {
  const headers = ['模块ID', '模块名称', '路径', '依赖个数', '被依赖个数', '大小', '内存占用', '引用进程']
  const csvRows = []

  // 添加文件头信息
  csvRows.push(`# 模块数据导出`)
  csvRows.push(`# 产品名称: ${productName}`)
  csvRows.push(`# 产品版本: ${productVersion}`)
  csvRows.push(`# 导出时间: ${new Date().toLocaleString()}`)
  csvRows.push(`# 模块数量: ${data.length}`)
  csvRows.push(`# 导出范围: 全部模块数据`)
  csvRows.push('')

  // 添加表格头部
  csvRows.push(headers.join(','))

  // 添加数据行
  data.forEach(module => {
    const row = [
      `"${module.id || ''}"`,
      `"${module.name || ''}"`,
      `"${module.path || ''}"`,
      `"${module.dependencies || 0}"`,
      `"${module.dependedBy || 0}"`,
      `"${module.size || 0}"`,
      `"${module.pss || 0}"`,
      `"${(module.procesess || '').replace(/"/g, '""')}"` // 转义引号
    ]
    csvRows.push(row.join(','))
  })

  // 添加统计信息
  csvRows.push('')
  csvRows.push('# 统计信息')

  const totalSize = data.reduce((sum, item) => sum + (item.size || 0), 0)
  const totalPSS = data.reduce((sum, item) => sum + (item.pss || 0), 0)
  const totalDeps = data.reduce((sum, item) => sum + (item.dependencies || 0), 0)

  csvRows.push(`# 总大小: ${formatBytes(totalSize)}`)
  csvRows.push(`# 总内存占用: ${formatBytes(totalPSS)}`)
  csvRows.push(`# 总依赖数: ${totalDeps}`)

  // 按类型统计
  const dylibCount = data.filter(m => m.name && m.name.includes('.dylib')).length
  const execCount = data.length - dylibCount
  csvRows.push(`# 动态库: ${dylibCount}`)
  csvRows.push(`# 可执行文件: ${execCount}`)

  return csvRows.join('\n')
}

// 获取搜索类型文本
const getSearchTypeText = () => {
  switch (searchForm.type) {
    case 'dylib': return '动态库'
    case 'executable': return '可执行文件'
    default: return '全部'
  }
}

const handleSearch = () => {
  pagination.current = 1
}

const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.type = ''
  sortState.field = null
  sortState.order = null
  pagination.current = 1
}

// 处理排序变化
const onSortChange = ({ prop, order }) => {
  // 将列名映射到排序字段
  const fieldMap = {
    'name': 'name',
    'dependencies': 'dependencies',
    'dependedBy': 'dependedBy',
    'size': 'size',
    'memory': 'memory',
    'processCount': 'processCount'
  }

  sortState.field = fieldMap[prop] || null
  sortState.order = order

  // 重置到第一页
  pagination.current = 1
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.current = 1
}

const handleCurrentChange = (page) => {
  pagination.current = page
}


const viewModuleDetail = (moduleId) => {
  // 使用路由跳转到详情页面
  try {
    router.push({
      name: 'ModuleDetail',
      params: { id: moduleId }
    }).catch(error => {
      console.warn('Navigation error:', error)
      // 如果路由跳转失败，回退到对话框方式
      selectedModuleId.value = moduleId
      detailDialogVisible.value = true
    })
  } catch (error) {
    console.warn('Navigation error:', error)
    // 回退到对话框方式
    selectedModuleId.value = moduleId
    detailDialogVisible.value = true
  }
}

const viewDependencies = (moduleId) => {
  try {
    // 导航到分析页面的依赖关系图
    router.push({
      name: 'Analysis',
      query: { module: moduleId, view: 'dependencies' }
    }).catch(error => {
      console.warn('Navigation to analysis failed:', error)
      // 如果路由跳转失败，显示提示消息
      ElMessage.info('依赖关系查看功能开发中')
    })
  } catch (error) {
    console.warn('Navigation error:', error)
    ElMessage.info('依赖关系查看功能开发中')
  }
}

// 直接打开依赖上下文对话框
const openDependencyDialog = (moduleId) => {
  selectedModuleId.value = moduleId
  detailDialogVisible.value = true
}

const handleDetailClose = () => {
  detailDialogVisible.value = false
  selectedModuleId.value = null
}

const handleOpenDependencyContext = (moduleId) => {
  // 关闭当前弹框
  detailDialogVisible.value = false

  // 延迟打开新的依赖上下文弹框，避免冲突
  setTimeout(() => {
    selectedModuleId.value = moduleId
    detailDialogVisible.value = true
  }, 300)
}

const getProcessList = (processes) => {
  if (!processes) return []
  return processes.split(',').slice(0, 3)
}

// 生命周期
onMounted(() => {
  modulesStore.initialize()
})
</script>

<style scoped lang="scss">
.modules-page {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .header-content {
      .page-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .page-description {
        margin: 0;
        color: var(--el-text-color-secondary);
      }
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .search-card {
    margin-bottom: 20px;

    .search-form {
      .el-form-item {
        margin-bottom: 0;
      }
    }
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 20px;

    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        gap: 16px;

        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .stat-info {
          .stat-value {
            font-size: 24px;
            font-weight: 600;
            color: var(--el-text-color-primary);
            line-height: 1;
          }

          .stat-label {
            font-size: 14px;
            color: var(--el-text-color-secondary);
            margin-top: 4px;
          }
        }
      }
    }
  }

  .table-card {
    .el-table {
      .el-link {
        font-weight: 500;
      }
    }

    .pagination-wrapper {
      margin-top: 20px;
      text-align: right;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .modules-page {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .header-actions {
        width: 100%;
        justify-content: flex-end;
      }
    }

    .stats-grid {
      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
      gap: 12px;

      .stat-card .stat-content {
        flex-direction: column;
        text-align: center;
        gap: 8px;
      }
    }

    .search-form {
      .el-form-item {
        display: block !important;
        margin-right: 0 !important;
        margin-bottom: 12px !important;
      }
    }
  }
}
</style>